import * as THREE from 'three';
import { GLTFLoader } from 'three/examples/jsm/loaders/GLTFLoader.js';
import { DRACOLoader } from 'three/examples/jsm/loaders/DRACOLoader.js';
import { gsap } from 'gsap';
import { BaseScene } from './BaseScene.js';

export class CarScene extends BaseScene {
    constructor(app, index) {
        super(app, index);
        this.name = '汽车场景';
        
        // 汽车模型相关
        this.carModel = null;
        this.carAnimations = [];
        this.mixer = null;
        
        // 场景特定设置
        this.cameraPosition.set(5, 3, 8);
        this.cameraTarget.set(0, 1, 0);
        
        // 环境设置
        this.ambientLightIntensity = 0.4;
        this.directionalLightIntensity = 1.5;
        
        // 动画参数
        this.rotationSpeed = 0.005;
        this.isCarLoaded = false;
        
        // GLTF加载器
        this.gltfLoader = new GLTFLoader();
        this.dracoLoader = new DRACOLoader();
        
        // 设置Draco解码器路径
        this.dracoLoader.setDecoderPath('https://www.gstatic.com/draco/v1/decoders/');
        this.gltfLoader.setDRACOLoader(this.dracoLoader);
    }
    
    async createObjects() {
        // 从预加载的模型中获取汽车模型
        await this.loadCarModel();
        
        // 创建环境
        this.createEnvironment();

    }
    
    async loadCarModel() {
        try {
            console.log('获取预加载的汽车模型...');
            
            // 从App3D获取预加载的模型
            const preloadedModel = this.app.getPreloadedModel('yuanqu');
            
            if (preloadedModel) {
                // 使用预加载的模型
                console.log('使用预加载的汽车模型');
                this.carModel = preloadedModel.scene.clone();
                
                // 保存动画
                if (preloadedModel.animations && preloadedModel.animations.length > 0) {
                    this.carAnimations = preloadedModel.animations;
                    this.mixer = new THREE.AnimationMixer(this.carModel);
                    
                    // 播放所有动画
                    this.carAnimations.forEach((clip) => {
                        const action = this.mixer.clipAction(clip);
                        action.play();
                    });
                }
            } else {
                // 如果预加载失败，回退到直接加载
                console.warn('预加载的汽车模型不可用，回退到直接加载');
                await this.loadCarModelDirect();
                return;
            }
            
            this.setupCarModel();
            this.isCarLoaded = true;
            console.log('汽车模型设置完成！');
            
            // 模型设置完成后的入场动画
            this.playCarIntroAnimation();
            
        } catch (error) {
            console.error('汽车模型加载失败:', error);
            
            // 加载失败时创建一个替代的简单汽车模型
            this.createFallbackCar();
        }
    }
    
    /**
     * 直接加载汽车模型（备用方案）
     */
    async loadCarModelDirect() {
        const modelUrl = 'https://prod-ylzapp-public.oss-cn-zhangjiakou.aliyuncs.com/frontend/yun-material/user-upload/1715075225235_通用小车1（带鲜生活标志）.gltf';
        
        console.log('直接从网络加载汽车模型...');
        
        const gltf = await new Promise((resolve, reject) => {
            this.gltfLoader.load(
                modelUrl,
                (gltf) => resolve(gltf),
                (progress) => {
                    const percent = (progress.loaded / progress.total) * 100;
                    console.log(`汽车模型加载进度: ${percent.toFixed(1)}%`);
                },
                (error) => reject(error)
            );
        });
        
        this.carModel = gltf.scene;
        // 保存动画
        if (gltf.animations && gltf.animations.length > 0) {
            this.carAnimations = gltf.animations;
            this.mixer = new THREE.AnimationMixer(this.carModel);
            
            // 播放所有动画
            this.carAnimations.forEach((clip) => {
                const action = this.mixer.clipAction(clip);
                action.play();
            });
        }
        
        this.setupCarModel();
    }
    
    /**
     * 设置汽车模型
     */
    setupCarModel() {
        if (!this.carModel) return;
            
        // 调整模型大小和位置
        this.carModel.scale.setScalar(0.1); // 根据模型大小调整
        this.carModel.position.set(0, 0, 0);
        this.carModel.rotation.y = Math.PI; // 让车头朝向相机
        console.log('this.carModel', this.carModel);
        // 设置阴影
        this.carModel.traverse((child) => {
            // 查询模型名称为‘沈阳仓园区周边’的模型，隐藏起来
            if (child.name === '沈阳仓园区周边') {
                child.visible = false;
            }
            if (child.isMesh) {
                child.castShadow = true;
                child.receiveShadow = true;
                
                // 优化材质
                if (child.material) {
                    child.material.envMapIntensity = 0.5;
                }
            }
        });
        
        // 简单添加模型到场景（自动分帧加载）
        console.log('About to call addObject for car model');
        this.addObject(this.carModel);
        console.log('addObject called for car model');
    }
    
    createFallbackCar() {
        console.log('创建替代汽车模型...');
        
        // 创建简单的汽车形状
        const carGroup = new THREE.Group();
        
        // 车身
        const bodyGeometry = new THREE.BoxGeometry(4, 1.5, 2);
        const bodyMaterial = new THREE.MeshPhongMaterial({ color: 0x3366ff });
        const body = new THREE.Mesh(bodyGeometry, bodyMaterial);
        body.position.y = 1;
        body.castShadow = true;
        body.receiveShadow = true;
        carGroup.add(body);
        
        // 车顶
        const roofGeometry = new THREE.BoxGeometry(2.5, 1, 1.8);
        const roofMaterial = new THREE.MeshPhongMaterial({ color: 0x2255dd });
        const roof = new THREE.Mesh(roofGeometry, roofMaterial);
        roof.position.set(-0.3, 2, 0);
        roof.castShadow = true;
        roof.receiveShadow = true;
        carGroup.add(roof);
        
        // 车轮
        const wheelGeometry = new THREE.CylinderGeometry(0.4, 0.4, 0.3);
        const wheelMaterial = new THREE.MeshPhongMaterial({ color: 0x333333 });
        
        const wheelPositions = [
            [-1.3, 0.4, 1.2],
            [-1.3, 0.4, -1.2],
            [1.3, 0.4, 1.2],
            [1.3, 0.4, -1.2]
        ];
        
        wheelPositions.forEach(pos => {
            const wheel = new THREE.Mesh(wheelGeometry, wheelMaterial);
            wheel.position.set(...pos);
            wheel.rotation.z = Math.PI / 2;
            wheel.castShadow = true;
            wheel.receiveShadow = true;
            carGroup.add(wheel);
        });
        
        // 车灯
        const lightGeometry = new THREE.SphereGeometry(0.2);
        const lightMaterial = new THREE.MeshPhongMaterial({ 
            color: 0xffff00,
            emissive: 0x444400
        });
        
        const frontLightPositions = [
            [1.8, 1.2, 0.7],
            [1.8, 1.2, -0.7]
        ];
        
        frontLightPositions.forEach(pos => {
            const light = new THREE.Mesh(lightGeometry, lightMaterial);
            light.position.set(...pos);
            carGroup.add(light);
        });
        
        this.carModel = carGroup;
        this.addObject(this.carModel);
        this.isCarLoaded = true;
        
        console.log('替代汽车模型创建完成');
        this.playCarIntroAnimation();
    }
    
    playCarIntroAnimation() {
        if (!this.carModel) return;
        
        // 入场动画：从上方降落
        this.carModel.position.y = 10;
        this.carModel.rotation.x = Math.PI / 4;
        
        gsap.timeline()
            .to(this.carModel.position, {
                duration: 2,
                y: 0,
                ease: "bounce.out"
            })
            .to(this.carModel.rotation, {
                duration: 1.5,
                x: 0,
                ease: "power2.out"
            }, "-=1")
            .to(this.carModel.rotation, {
                duration: 3,
                y: this.carModel.rotation.y + Math.PI * 2,
                ease: "power2.inOut"
            }, "-=0.5");
    }
    
    createEnvironment() {
        // 创建天空盒效果
        const skyGeometry = new THREE.SphereGeometry(100, 32, 32);
        const skyMaterial = new THREE.MeshBasicMaterial({
            color: 0x87CEEB,
            side: THREE.BackSide,
            fog: false
        });
        const sky = new THREE.Mesh(skyGeometry, skyMaterial);
        this.addObject(sky);
        
        // 添加雾效果
        this.app.scene.fog = new THREE.Fog(0x87CEEB, 10, 100);
    }

    
    updateObjects() {
        // 调用父类的updateObjects来更新分帧加载器
        super.updateObjects();
        
        // 汽车场景特定的更新逻辑
        const time = performance.now() * 0.001;
        
        // 更新环境光照
        if (this.directionalLight) {
            // 模拟太阳光的移动
            const sunAngle = time * 0.1;
            this.directionalLight.position.x = Math.cos(sunAngle) * 10;
            this.directionalLight.position.y = 8;
            this.directionalLight.position.z = Math.sin(sunAngle) * 10;
            this.directionalLight.lookAt(0, 0, 0);
        }
    }
    
    activate() {
        super.activate();
        
        // 激活时的特殊效果
        if (this.carModel && this.isCarLoaded) {
            // 闪烁效果
            gsap.to(this.carModel.scale, {
                duration: 0.5,
                x: 1.1,
                y: 1.1,
                z: 1.1,
                yoyo: true,
                repeat: 1,
                ease: "power2.inOut"
            });
        }
    }
    
    adjustParticleCount(factor) {
        // 根据性能调整装饰灯光数量
        // this.objects.forEach(obj => {
        //     if (obj instanceof THREE.PointLight) {
        //         obj.intensity = obj.intensity * factor;
        //     }
        // });
    }
    
    onResize(width, height) {
        super.onResize(width, height);
        
        // 汽车场景特定的响应式调整
        const aspect = width / height;
        
        if (aspect < 1) {
            // 移动设备适配：调整相机位置
            this.cameraPosition.set(8, 4, 10);
        } else {
            // 桌面设备
            this.cameraPosition.set(5, 3, 8);
        }
    }
    
    dispose() {
        // 清理GLTF资源
        if (this.mixer) {
            this.mixer.stopAllAction();
            this.mixer = null;
        }
        
        if (this.dracoLoader) {
            this.dracoLoader.dispose();
        }
        
        // 清理雾效果
        if (this.app.scene.fog) {
            this.app.scene.fog = null;
        }
        
        super.dispose();
        
        console.log('汽车场景资源已清理');
    }
}
